package com.hwd.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.hwd.srb.common.exception.Assert;
import com.hwd.srb.common.result.ResponseEnum;
import com.hwd.srb.core.mapper.DictMapper;
import com.hwd.srb.core.pojo.dto.ExcelDictDTO;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 黄伟东/Victor
 * @date 2022/3/14 17:49
 * @Description 监听者
 */
@Slf4j
@NoArgsConstructor
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    private DictMapper dictMapper;

    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;

    public static Long count = 0L;

    private List<ExcelDictDTO> excelDictDTOList = new ArrayList<>();
    ;

    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    /**
     * 解析完一条数据后的回调函数
     */
    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext context) {

        log.info("解析到1条数据：{}", data);

        excelDictDTOList.add(data);
        count++;

        if (count % BATCH_COUNT == 0) {

            log.info("将" + excelDictDTOList.size() + "条数据插入数据库，共插入" + count + "条数据");
            dictMapper.insertBatch(excelDictDTOList);

            excelDictDTOList.clear();
        }
    }

    /**
     * 解析完全部数据后的回调函数
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

        if (count % BATCH_COUNT != 0) {

            log.info(count + "条数据已全部解析完成，将剩余" + excelDictDTOList.size() + "条数插入数据库");
            dictMapper.insertBatch(excelDictDTOList);

            excelDictDTOList.clear();
        }

        log.info(count + "条数据已全部解析完成，并全部插入数据库");
        count = 0L;
    }
}
